package com.ittx.dzt.jinglyun.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.OrderGetDTO;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.jinglyun.handler.AbstractBaseJinglYunApiHandler;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据订单号下载订单详情
 * <p>
 * cy.salesOrder.download.byOrderId
 * /open/api/order/listOrders  查询发货单详情
 * https://jlopen.jinglyun.com/main/doc?docType=2&cateId=10001&docId=20012
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/10/20
 */
@Slf4j
@Service
public class JinglYunSalesOrderDownloadByIdService extends AbstractBaseJinglYunApiHandler<OrderGetDTO> {

	@Override
	public String getJinglMethod() {
		return "/open/api/order/listOrders";
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_ORDERID;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		// 参数校验
		Result<?> result = checkParams(platformApiParamDTO, orderGetDTO);
		if (result.hasError()) {
			return result;
		}
		List<Object> list = new ArrayList<>();
		String[] orderCodeArr = orderGetDTO.getOrderId().split(",");
		if (orderCodeArr.length > 0) {
			for (String code : orderCodeArr) {
				result = this.getOrderById(platformApiParamDTO, code);
				if (result.hasError()) {
					return result;
				}
				Object resultData = result.getData();
				// 同步返回
				if (orderGetDTO.getIsAsync() == 0) {
					list.add(resultData);
				} else {
					platformApiParamDTO.setPlatformIdentifierTag(code);
					result = this.sendRequestToPlatform(platformApiParamDTO, resultData, true);
					if (!result.isSuccess()) {
						return result;
					}
				}
			}
		}
		// 同步返回
		if (orderGetDTO.getIsAsync() == 0) {
			return Result.success().addData(list).addMsg(platformApiParamDTO.getStoreConfig().getChainUniqueCode());
		}
		return Result.success();
	}


	/**
	 * 根据id获取订单
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return
	 */
	public Result<?> getOrderById(PlatformApiParamDTO platformApiParamDTO, String id) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.getOrderBySdk(platformApiParamDTO, id);
	}

	/**
	 * 执行api请求
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return 请求结果 resultMap.get(DATA_FIELD)
	 */
	public Result<?> getOrderBySdk(PlatformApiParamDTO platformApiParamDTO, String id) {
		Map<String, Object> params = new HashMap<>();
		// orderIds	Array	是	发货单ID数组（Long型数组），最大数量50个
		params.put("orderIds", Lists.newArrayList(Long.valueOf(id)));
		String requestId = platformApiParamDTO.getRequestId();
		Result<?> result = this.executeApi(platformApiParamDTO, params, requestId);
		if (result.hasError()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		List saleDataList = MapUtil.get(resultMap, "entry", List.class);
		if (CollUtil.isEmpty(saleDataList)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, platformApiParamDTO.getRequestId(), id);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}
		Object saleData = saleDataList.get(0);
		if (saleData == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, platformApiParamDTO.getRequestId(), id);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}
		return Result.success().addData(saleData);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param orderGetDTO         接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		if (orderGetDTO == null || platformApiParamDTO.getStoreConfig() == null || StrUtil.isBlank(orderGetDTO.getOrderId())) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), orderGetDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
